package com.shop.cereshop.app.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.HashMap;
import java.util.Map;

public class PinyinUtils {

    /**
     * 获取字符串的拼音首字母（大写，忽略非中文字符，取第一个中文字符的首字母）
     * 特殊处理常见城市名
     */
    public static String getFirstLetter(String input) {
        if (input == null || input.isEmpty()) {
            return "";
        }

        // 特殊处理常见城市名
        Map<String, String> specialCases = new HashMap<>();
        specialCases.put("重庆市", "C");
        specialCases.put("上海市", "S");
        specialCases.put("北京市", "B");
        specialCases.put("天津市", "T");

        if (specialCases.containsKey(input)) {
            return specialCases.get(input);
        }

        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        for (char c : input.toCharArray()) {
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]")) {
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        String firstChar = String.valueOf(pinyinArray[0].charAt(0)).toUpperCase();

                        // 特殊处理"重"字，应该归到"C"组
                        if ("Z".equals(firstChar) && input.contains("重庆")) {
                            return "C";
                        }

                        return firstChar;
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }
}

